package priv.zhjm.demo.interceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import priv.zhjm.demo.entity.User;
import priv.zhjm.demo.util.Constants;
import priv.zhjm.demo.util.Jurisdiction;
import priv.zhjm.demo.util.Tools;

public class LoginHandlerInterceptor extends HandlerInterceptorAdapter {

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
			throws Exception {
		String path = request.getServletPath();
		Tools.isNull(path);
		System.out.println("---------->" + path);
		if (path.matches(Constants.NO_INTERCEPTOR_PATH)) {
			System.out.println("---------->1true");
			return true;
		} else {
			// shiro管理的session
			Subject currentUser = SecurityUtils.getSubject();
			Session session = currentUser.getSession();
			User user = (User) session.getAttribute(Constants.SESSION_USER);
			if (user != null) {
				path = path.substring(1, path.length());
				boolean b = Jurisdiction.hasJurisdiction(path);
				if (!b) {
					response.sendRedirect(request.getContextPath() + Constants.LOGIN);
				}
				System.out.println("---------->2true");
				return b;
			} else {
				response.sendRedirect(request.getContextPath() + Constants.LOGIN);
				System.out.println("---------->1false");
				return false;
			}
		}
	}
}
